package com.study.juc.volatiles;

import java.util.concurrent.TimeUnit;

/**
 * @program: juc-study
 * @author: jzhou
 * @date: 2022-08-15 20:55
 * @version: 1.0
 * @description: volatile 无原子性验证 ，多线程操作volatile修饰变量 i++ ，期望值 10000 但结果总是比10000小
 **/
public class VolatileNoAtomicDemo {
	public static void main(String[] args) throws InterruptedException {
		MyNumber myNumber = new MyNumber();

		for (int i = 1; i <= 10; i++) {
			new Thread(() -> {
				for (int j = 1; j <= 1000; j++) {
					myNumber.addPlusPlus();
				}
			}, String.valueOf(i)).start();
		}

		//暂停几秒钟线程
		try {
			TimeUnit.SECONDS.sleep(3);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() + "\t" + myNumber.number);
	}
}

class MyNumber {
	volatile int number = 0;

	public void addPlusPlus() {
		number++;
	}
}